import { Injectable } from '@nestjs/common';
const Minio = require('minio')
import { nanoid } from 'nanoid'

const minioIP = "101.132.222.222"

const minioClient = new Minio.Client({
    endPoint: minioIP,
    port: 9000,
    useSSL: false,
    accessKey: 'minioadmin',
    secretKey: 'minioadmin'
});

@Injectable()
export class OssService {
    async presignedUrl(bucket: string, userId: string) {
        //should have only create bucket in some conditions
        if (bucket == null) {
            return { status: 40000 }
        }
        let exists = await minioClient.bucketExists(bucket)
        if (!exists) {
            await minioClient.makeBucket(bucket)
        }
        let file_id = nanoid(12)
        let url = await minioClient.presignedPutObject(bucket, file_id)
        console.log(url)
        return { status: 20000, "url": url, "file_id": file_id, "exp_url": "http://" + minioIP + ":9000/" + bucket + "/" + file_id }
    }

    presignedGetUrl(bucket: string, file_id: string) {
        minioClient.presignedGetObject(bucket, file_id, 5 * 60, function (err, presignedGetUrl) {
            if (err) return (err)
            return { status: 20000, url: presignedGetUrl }
        })
    }

    statObject(bucket: string, file_id: string) {
        minioClient.statObject(bucket, file_id, function (err, stat) {
            if (err) {
                return (err)
            }
            return { status: 20000, file_info: stat }
        })
    }
}
